package com.bigfans.framework.jms;

import java.io.Serializable;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;

/**
 * @Description:
 * @author lichong
 * @date Oct 18, 2016 7:21:00 PM
 * 
 */
public class JmsTemplate {

	private ConnectionFactory connectionFactory;
	
	public JmsTemplate(JmsConnectionFactory connectionFactory) {
		this.connectionFactory = connectionFactory;
	}

	public ConnectionFactory getConnectionFactory() {
		return connectionFactory;
	}

	public void setConnectionFactory(ConnectionFactory connectionFactory) {
		this.connectionFactory = connectionFactory;
	}

	public void sendObjectMsg(String topic, final Serializable msgObj) {
		this.send(topic, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				return session.createObjectMessage(msgObj);
			}
		});
	}
	
	public void sendTextMsg(String topic, final String msgStr) {
		this.send(topic, new MessageCreator() {
			public Message createMessage(Session session) throws JMSException {
				return session.createTextMessage(msgStr);
			}
		});
	}
	
	public void send(String topic, MessageCreator messageCreator){
		this.execute(topic, messageCreator);
	}

	private void execute(String topic, MessageCreator messageCreator) {
		Connection connection = null;
		MessageProducer messageProducer = null;
		Session session = null;
		try {
			// 通过连接工厂获取连接
			connection = connectionFactory.createConnection();
			// 启动连接
			connection.start();
			// 创建session
			session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
			// 消息的目的地 , 创建一个名称为HelloWorld的消息队列
			Destination destination = session.createQueue(topic);
			// 创建消息生产者
			messageProducer = session.createProducer(destination);
			// 发送消息
			Message message = messageCreator.createMessage(session);
			messageProducer.send(message);
			session.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (messageProducer != null) {
				try {
					messageProducer.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
			if (session != null) {
				try {
					session.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
			if (connection != null) {
				try {
					connection.close();
				} catch (JMSException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
